<template>
  <div>
    <movie-list :list="list"></movie-list>
    <infinite-loading @infinite="infiniteHandler" spinner="spiral"></infinite-loading>
    <loading :show="initing"></loading>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import * as types from '@/store/types'
import InfiniteLoading from 'vue-infinite-loading'
import MovieList from '@/components/m/movie-list'
import Loading from '@/components/loading'

export default {
  components: { Loading, MovieList, InfiniteLoading },
  computed: mapState({
    list: state => state.movie.list,
    total: state => state.movie.total,
    initing: state => state.movie.initing
  }),
  created () {
    this.$store.dispatch({
      type: types.FETCH_TOP_250,
      start: 0,
      count: 30
    })
  },
  methods: {
    infiniteHandler ($state) {
      if (!this.initing) {
        this.$store.dispatch({
          type: types.FETCH_TOP_250,
          count: 10
        }).then(() => {
          this.list.length >= this.total ? $state.complete() : $state.loaded()
        })
      } else {
        $state.reset()
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    this.$store.commit(types.RESET_MOVIE_STATE)
    next()
  }
}
</script>
